#include "heartRequest.h"
#include "adLogic.h"

//解析命令
void pearsCmd(cJSON* cmdList)
{
    //判断是不是数组
    if(!cJSON_IsArray(cmdList))
    {
        return;
    }
    //获取数组的size
    int size = cJSON_GetArraySize(cmdList);
    for (int i = 0; i < size; i++)
    {
        //获取对应的元素
        cJSON* item = cJSON_GetArrayItem(cmdList,i);
        if (cJSON_IsNumber(item))
        {
            int cmdId = item->valueint;
            printf("index[%d]:cmdId: %d\n", i, cmdId);
            switch (cmdId)
            {
            case 1:
            //关机
                //system(" echo yaosang | sudo -S shutdown -h now "); 
                break;
            case 2:
            //重启   reboot
                //system("echo yaosang | sudo -S reboot");
                break;
            case 3:
            //检查更新
                break;
            
            default:
                break;
            }
        }
    }
}

//请求的回调
size_t heartCallback(char *contents,size_t size,size_t nmemb,void *userp)
{
    size_t realszie = size*nmemb;
    char * result = (char *)contents;
    cJSON* jsonStr = cJSON_Parse(result);
    if (jsonStr != NULL)
    {
        cJSON * successStr = cJSON_GetObjectItemCaseSensitive(jsonStr,"success");
        cJSON * messageStr = cJSON_GetObjectItemCaseSensitive(jsonStr,"message");
    
        if (cJSON_IsFalse(successStr))
        {
            printf("%s\n",messageStr->valuestring);
            return -1;
        }

        cJSON *dataStr = cJSON_GetObjectItemCaseSensitive(jsonStr,"data");
        cJSON *AdListStr = cJSON_GetObjectItemCaseSensitive(jsonStr,"ad_list");
        cJSON *CmdListStr = cJSON_GetObjectItemCaseSensitive(jsonStr,"cmd_list");

        pearsCmd(CmdListStr);//解析命令cmd
        handleAdList(AdListStr);
    }
    return realszie;

}
//1.获取当前请求的内容
//2.如果请求成功解析里面的指令集 和 广告列表


//发送心跳请求
void sendHeartRequest(char* ip,char* sn)
{
    char *url = "http://%s/config.json?sn=%s";
    char *realUrl = calloc(1,100);
    sprintf(realUrl,url,ip,sn);
    printf("request address:%s\n",realUrl);

    //发送一个get请求
    sendGetRequest(realUrl,heartCallback);
}